#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

cpulimit_get() {
	local enabled
	local limit
	local exename
	local numcores
	local include_children
	config_get_bool enabled $1 enabled 0
	[ "$enabled" -eq 1 ] || return 1
	config_get limit $1 limit
	[ -z "$limit" ] && return 1
	numcores="$(cpulimit -h | awk -F 'percentage of cpu allowed from 0 to ' '/^[[:space:]]*-l, --limit=N/{print $2; exit}' | awk '{print $1/100; exit}')"
	[ "$limit" -gt 0 -a "$limit" -le $((100 * numcores)) ] || return 1
	config_get exename $1 exename
	[ -z "$exename" ] && return 1
	exename="$(basename "$exename")"
	config_get_bool include_children $1 include_children 0

	procd_open_instance
	procd_set_param command cpulimit
	procd_append_param command -l "$limit"
	procd_append_param command -e "$exename"
	[ "$include_children" -eq 1 ] && procd_append_param command -i
	procd_set_param stderr 1
	procd_set_param nice -20
	procd_set_param respawn
	procd_close_instance
}

start_service() {
	config_load cpulimit
	config_foreach cpulimit_get list
}

service_triggers() {
	procd_add_reload_trigger "cpulimit"
}
